package com.wgj.android.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.imagepicker.Utils.ImagePickerUtils;
import com.jiaai.xui.imagepicker.Utils.Utils;
import com.jiaai.xui.imagepicker.entity.XIMGEventEntry;
import com.jiaai.xui.utils.XAppUtils;
import com.jiaai.xui.utils.XCameraUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.XPreferencesUtils;
import com.jiaai.xui.utils.http.BaseHttpCallBack;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.http.entity.VUpload;
import com.jiaai.xui.utils.imageload.XImage;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.XTakePhotosDialog;
import com.jiaai.xui.view.widget.XLoadingDialog;

import com.jiaai.xui.view.widget.XToast;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wgj.android.R;
import com.wgj.android.entity.Member;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.widget.imageselect.ImagePicker;
import com.wgj.android.widget.imageselect.cropper.CropImage;
import com.wgj.android.widget.imageselect.cropper.CropImageView;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/11/3.
 */

public class MyInfoActivity extends AppCompatActivity  implements XTakePhotosDialog.OnTakePhotosListener{
    @BindView(R.id.avater)
    ImageView avaterImageView;

    @BindView(R.id.nickNameTextView)
    TextView nickNameTextView;

    @BindView(R.id.shareContentTextView)
    TextView shareConterTextView;

    @BindView(R.id.cname)
    TextView cname;
    private  String filePath;

    @BindView(R.id.weixiStatus)
    TextView weixiStatus;

    private ImagePicker imagePicker;
    private UploadManager uploadManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.my_info_activity);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);

         imagePicker = new ImagePicker();
        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(true);

    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 修改头像
     * @param view
     */
    @OnClick(R.id.avater)
    public void  onUupdateAvater(View view){
        new XTakePhotosDialog(this,R.style.dialog_setting).setTakePhotosListener(this).show();
    }

    @OnClick(R.id.nikcNameItem)
    public void  updateNickName(View view){
            Intent intent=new Intent(getApplication(),EditNickNameActivity.class);
            startActivity(intent);
    }


    @OnClick(R.id.editShareContentBut)
    public void  updateShare(View view){
        Intent intent=new Intent(getApplication(),EditShareContentActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.editPassword)
    public  void editPassword(View view){
        Intent intent=new Intent(getApplication(),FindPwdActivity.class);
        startActivity(intent);
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * 修改头像
     * @param path
     */
    private  void uploadAvater(final String path){

        XLoadingDialog.with(this).show();
        Map<String,File> params=new HashMap<>();
        params.put("file",new File(path));
        XHttp.obtain().upload("wgj", params, new ListHttpCallBack<VUpload>() {
            @Override
            public void onSuccess(final List<VUpload> list) {

                String path =list.get(0).getFilePath();
                final Member member= CacheUtils.getMember();
                Map<String,Object> params=new HashMap<>();
                params.put("mId",member.getM_id());
                params.put("avater",path);
                final String finalPath = path;
                XHttp.obtain().post(WGJAPI.UPDATE_MEMBER_API, params, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String s) {
                        member.setAvater(finalPath);
                        XImage.getInstance().load(avaterImageView,member.getAvater());
                        try {
                            CacheUtils.setMember(member);
                        }catch (Exception e){

                        }
                        XLoadingDialog.with(MyInfoActivity.this).dismiss();
                        XToast.success("修改成功");
                    }
                    @Override
                    public void onFailed(int i, String s, boolean b) {
                         XToast.error("修改失败");
                        XLoadingDialog.with(MyInfoActivity.this).dismiss();
                    }
                });
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.error("上传头像失败");
                XLoadingDialog.with(MyInfoActivity.this).dismiss();
            }
        });
    }
    /*private void upload(final String uploadToken, final String domain,String path) {
        if (this.uploadManager == null) {
            this.uploadManager = new UploadManager();
        }
        File uploadFile = new File(path);
        this.uploadManager.put(uploadFile, null, uploadToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo,
                                         JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                String fileKey = jsonData.getString("key");
                                DisplayMetrics dm = new DisplayMetrics();
                                getWindowManager().getDefaultDisplay().getMetrics(dm);
                                final int width = dm.widthPixels;
                                final OkHttpClient httpClient = new OkHttpClient();
                                final String imageUrl = domain + "/" + fileKey + "?imageView2/0/w/" + width + "/format/jpg";
                                upload(imageUrl);//上传到自己的服务器

                            } catch (JSONException e) {
                                Toast.makeText(MyInfoActivity.this,
                                        "上传回复解析错误!",
                                        Toast.LENGTH_LONG).show();
                                XLoadingDialog.with(MyInfoActivity.this).dismiss();
                            }
                        } else {
                            Toast.makeText(
                                    MyInfoActivity.this,
                                    "上传文件失败",
                                    Toast.LENGTH_LONG).show();
                            XLoadingDialog.with(MyInfoActivity.this).dismiss();

                        }
                    }

                }, null);
    }*/

    @Override
    public void onTakePictureClick() {

        imagePicker.startCamera(this, new ImagePicker.Callback() {
            @Override
            public void onPickImage(Uri imageUri) {


            }
            // 自定义裁剪配置
            @Override public void cropConfig(CropImage.ActivityBuilder builder) {
                builder
                        // 是否启动多点触摸
                        .setMultiTouchEnabled(false)
                        // 设置网格显示模式
                        .setGuidelines(CropImageView.Guidelines.OFF)
                        // 圆形/矩形
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        // 调整裁剪后的图片最终大小
                        .setRequestedSize(360, 360)
                        // 宽高比
                        .setAspectRatio(1, 1);
            }
            @Override
            public void onCropImage(Uri imageUri) {
                filePath= imageUri.getPath();
                uploadAvater(filePath);
            }
        });
        ///XCameraUtils.openCamera(this,filePath);
    }
    @Override
    public void onChoosePictureClick() {

        imagePicker.startGallery(this, new ImagePicker.Callback() {
                @Override
                public void onPickImage(Uri imageUri) {
                }
                // 自定义裁剪配置
                @Override public void cropConfig(CropImage.ActivityBuilder builder) {
                    builder
                            // 是否启动多点触摸
                            .setMultiTouchEnabled(false)
                            // 设置网格显示模式
                            .setGuidelines(CropImageView.Guidelines.OFF)
                            // 圆形/矩形
                            .setCropShape(CropImageView.CropShape.RECTANGLE)
                            // 调整裁剪后的图片最终大小
                            .setRequestedSize(360, 360)
                            // 宽高比
                            .setAspectRatio(1, 1);
                }
                @Override
                public void onCropImage(Uri imageUri) {
                    filePath= imageUri.getPath();
                    uploadAvater(filePath);
                }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
        public void photosMessageEvent(XIMGEventEntry entries){
        if (entries.id == XIMGEventEntry.RECEIVED_PHOTOS_ID) {
            if(entries.photos.size()>0){
                uploadAvater(entries.photos.get(0).getPath());
            }
        }
    }



    @Override
    protected void onResume() {
        Member member= CacheUtils.getMember();
        XImage.getInstance().load(avaterImageView,member.getAvater());
        cname.setText(member.getCname());
        nickNameTextView.setText(member.getM_nick());
        shareConterTextView.setText(member.getSharecontent());
        if(TextUtils.isEmpty(member.getUnionId())){
            weixiStatus.setText("未认证");
        }else {
            weixiStatus.setText("已认证");
        }
        super.onResume();
    }

    @OnClick(R.id.bindWeiXin)
    public void onBindWX(View view){
        Member member= CacheUtils.getMember();
        if(TextUtils.isEmpty(member.getUnionId())){
            SendAuth.Req req = new SendAuth.Req();
            String weixiAppId= XAppUtils.readMetaDataFromApplication("weiXinAppId");
            req.scope = "snsapi_userinfo";
            req.state="wechat_sdk_demo_test";
            WXAPIFactory.createWXAPI(this,weixiAppId, false).sendReq(req);
        }

    }
    public void upload(final String imgPath){
        final Member member= CacheUtils.getMember();
        Map<String,Object> params=new HashMap<>();
        params.put("mId",member.getM_id());
        params.put("avater",imgPath);
        XHttp.obtain().post(WGJAPI.UPDATE_MEMBER_API, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                member.setAvater(imgPath);
                XImage.getInstance().load(avaterImageView,imgPath);
                try {
                    CacheUtils.setMember(member);
                }catch (Exception e){

                }
                XLoadingDialog.with(MyInfoActivity.this).dismiss();
                XToast.success("修改成功");
            }
            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.error("修改失败");
                XLoadingDialog.with(MyInfoActivity.this).dismiss();
            }
        });
    }
}
